<script setup>
import {ref} from "vue";
import {useUserStore} from "@/stores/user";
import dayjs from "dayjs";
import SelectComponent from "@/components/Material/SelectComponent.vue";
import SelectUserComponent from "@/components/User/SelectComponent.vue";
import {addInventory} from "@/apis/inventory";
import {Message} from "tdesign-mobile-vue";
import {useRouter} from "vue-router"

const router = useRouter();
const store = useUserStore();
const token = store.token;
const formData = ref({
  date: dayjs().format("YYYY-MM-DD"),
  title: "领用单" + dayjs().format("YYYY-MM-DD"),
  name: "",
  record_user_id: store.user.id,
  user_id: 0,
  goods_list: [],
  voucher: []
})
const materialList = ref([])
const fileList = ref([])
const userVisible = ref(false)
const materialVisible = ref(false)
const ATTACH_URL = import.meta.env.VITE_ATTACH_URL;

function selectConfirm(item) {
  let find = false;
  materialList.value.forEach((el, index) => {
    if (el.id === item.id) {
      el.total = el.total++;
      materialList.value[index] = el;
      find = true;
    }
  })
  if (find === false) {
    materialList.value.push(item)
  }
  materialVisible.value = false
}

function selectUserConfirm(item) {
  formData.value.user_id = item.id
  formData.value.name = item.profile.name
  userVisible.value = false
}

function deleteMaterial(index) {
  materialList.value.splice(index, 1);
}

function formatRes(e) {
  if (e.code === 1) {
    formData.value.cover = e.data.key
    return {
      url: ATTACH_URL + "/" + e.data.key,
      key: e.data.key
    }
  } else {
    return {
      error: e.msg,
    }
  }
}

function submitFunc() {
  formData.value.type = 0;
  formData.value.goods_list = materialList.value;
  formData.value.voucher = [];
  fileList.value.forEach(item => {
    formData.value.voucher.push({
      name: item.name,
      key: item.response.key
    })
  })
  addInventory(formData.value)
      .then(res => {
        const {code, msg} = res.data;
        if (code === 1) {
          Message.success({
            content: msg,
            context: document.querySelector('main'),
            offset: [8, 8]
          })
          setTimeout(() => {
            router.back()
          }, 2000);
        } else {
          Message.error({
            content: msg,
            context: document.querySelector('main'),
            offset: [8, 8]
          })
        }
      })
}
</script>
<template>
  <main>
    <t-form>
      <t-cell-group title="领用清单">
        <t-form-item requiredMark label="领用人">
          <t-input readonly borderless v-model="formData.name" placeholder="请填写用户信息"
                   @click="userVisible = true"></t-input>
        </t-form-item>
        <t-form-item label="记录人">
          <t-input borderless readonly :value="store.user.profile.name"></t-input>
        </t-form-item>
      </t-cell-group>
    </t-form>
    <t-cell-group title="物品列表">
      <t-cell v-for="(item, index) in materialList" :key="item.id" :title="item.name" :image="item.cover_info?.url">
        <template #description>
          <t-tag style="margin-bottom: 8px;">物品编码：{{ item.material_id }}</t-tag>
          <t-stepper v-model="materialList[index].total" theme="filled"/>
        </template>
        <template #rightIcon>
          <t-icon @click="deleteMaterial(index)" name="delete-1" style="color: red;"></t-icon>
        </template>
      </t-cell>
      <t-cell>
        <template #note>
          <t-icon @click="materialVisible = true" size="30" name="add-circle"
                  style="margin-right: 8px;color: #535d6d;"/>
          <t-icon size="30" name="scan" style="color: #535d6d;"/>
        </template>
      </t-cell>
    </t-cell-group>
    <t-cell-group title="上传凭证">
      <div style="background-color: white;">
        <t-upload v-model="fileList" multiple :max="10" :grid-config="{ column: 4 }" :action="ATTACH_URL"
                  :formatResponse="formatRes"
                  :headers="{ Authorization: token }">
        </t-upload>
      </div>
    </t-cell-group>
    <div style="margin: 8px;">
      <t-button type="submit" theme="primary" block @click="submitFunc">保存</t-button>
    </div>
    <t-popup v-model="userVisible" placement="bottom">
      <div class="header">
        <div class="btn btn--cancel" aria-role="button" @click="userVisible=false">
          <t-icon name="chevron-down"></t-icon>
        </div>
        <div class="title">请选择领用人</div>
        <div class="btn btn--confirm" aria-role="button" @click="userVisible=false"></div>
      </div>
      <SelectUserComponent @confirm="selectUserConfirm"></SelectUserComponent>
    </t-popup>

    <t-popup v-model="materialVisible" placement="bottom">
      <div class="header">
        <div class="btn btn--cancel" aria-role="button" @click="materialVisible=false">
          <t-icon name="chevron-down"></t-icon>
        </div>
        <div class="title">请选择物品</div>
        <div class="btn btn--confirm" aria-role="button" @click="materialVisible=false"></div>
      </div>
      <SelectComponent @confirm="selectConfirm"/>
    </t-popup>
  </main>
</template>

<style scoped lang="less">
.header {
  display: flex;
  align-items: center;
  height: 116rpx;
}

.title {
  flex: 1;
  text-align: center;
  font-weight: 600;
  font-size: 18px;
  color: var(--td-text-color-primary, rgba(0, 0, 0, 0.9));
}

.btn {
  font-size: 16px;
  padding: 16px;
}

.btn--cancel {
  color: var(--td-text-color-secondary, rgba(0, 0, 0, 0.6));
}

.btn--confirm {
  color: #0052d9;
  width: 20px;
  height: 20px;
}
</style>